package vooga.xml.handlers;

import java.awt.Color;

import vooga.xml.XMLException;

/**
 * The XMLHandler for Vooga level definition files that parses Layers
 * based on FactoryHandler
 * @author Congyi Wu
 *
 */
public class LayerHandler extends vooga.xml.XMLHandler
{
    //XML constants
    public static final String LAYER_ENTITY = "layer";
    
    public static final String VALUE_ATTRIBUTE = "value";
    public static final String CLASS_ATTRIBUTE = "class";

    //rgb background color of layer (in hex, ie "ffffff" or "E2C232")
    public static final String BG_COLOR_ATTRIBUTE = "bgcolor";

    public vooga.core.Layer handleNode (org.w3c.dom.Node node, Object context) throws XMLException
    {
        try
        {
        	vooga.core.Layer result = (vooga.core.Layer)handleNodeHelper(node);
        	        	
        	int bgColor = result.getBackGroundColor().getRGB();
        	
        	try
        	{
        		bgColor = Integer.parseInt(getAttribute(node, BG_COLOR_ATTRIBUTE), 16);
        	}
        	catch(NumberFormatException e) {}

        	result.setBackGroundColor(new Color(bgColor));
        	
        	return result;
        }
        catch (Exception e)
        {
            throw new vooga.xml.XMLException("Could not handle " + node, e);
        }
    }
    
    private Object handleNodeHelper(org.w3c.dom.Node node) throws XMLException
    {
    	Object[] args = null;
        if (isComplete(node))
        {
            args = new Object[] { getAttribute(node, VALUE_ATTRIBUTE) };
        }
        else
        {
            java.util.List paramNodes = getSubNodes(node);
            args = new Object[paramNodes.size()];
            for (int k = 0; k < args.length; k++)
            {
                org.w3c.dom.Node current = (org.w3c.dom.Node)paramNodes.get(k);
                args[k] = getDocument().getHandler(current.getNodeName()).handleNode(current, null);
            }
        }
    	return vooga.util.Reflection.createInstance(getAttribute(node, CLASS_ATTRIBUTE), args);
    }

    protected boolean isComplete (org.w3c.dom.Node node)
    {
        return (getAttribute(node, VALUE_ATTRIBUTE) != null);
    }
}
